#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: sparql.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  an advance SPARQL Query Editor

import re
import datetime

import gtk
import pango

from rdflib import Literal

from vazaarlib.ui.widgets.customview import IconView
#from ui.widgets.customview import ListView

from vazaarlib.namespaces import *
from vazaarlib.utils import fuzzy_date, get_date_filtered_query, get_normal_query
from vazaarlib.utils import get_search_query

class StartHere:
    """ StartHere manager """

    def __init__(self, gui):
        self.gui = gui
        self.graph = self.gui.get_graph()

        self.gui.frontend['sh-dlgdelcol'] = self.gui.glade.widgets.get_widget("dlgDeleteCollection")

        # Search entry
        self.gui.frontend['sh-etysearch'] = self.gui.glade.widgets.get_widget("etySearch")
        self.gui.frontend['sh-chkfltview'] = self.gui.glade.widgets.get_widget("chkThisView")
        self.gui.frontend['sh-etysearch'].connect('activate', self.search)
        #self.gui.frontend['sh-chkfltview'].connect('toggled', self.filter_only_current_view)

        # Stats
        # Set Stats Buttons
        self.gui.frontend['sh-btntres'] = self.gui.glade.widgets.get_widget("btnTotResources")
        self.gui.frontend['sh-btntcol'] = self.gui.glade.widgets.get_widget("btnTotCollection")
        self.gui.frontend['sh-btntsin'] = self.gui.glade.widgets.get_widget("btnTotSingles")
        self.gui.frontend['sh-btntclp'] = self.gui.glade.widgets.get_widget("btnStatsClipboard")
        self.gui.frontend['sh-btnttxt'] = self.gui.glade.widgets.get_widget("btnStatsText")
        self.gui.frontend['sh-btntimg'] = self.gui.glade.widgets.get_widget("btnStatsImage")
        self.gui.frontend['sh-btntmus'] = self.gui.glade.widgets.get_widget("btnStatsAudio")
        self.gui.frontend['sh-btntvdo'] = self.gui.glade.widgets.get_widget("btnStatsVideo")
        self.gui.frontend['sh-btntweb'] = self.gui.glade.widgets.get_widget("btnStatsWebsite")
        self.gui.frontend['sh-btntfdd'] = self.gui.glade.widgets.get_widget("btnStatsFeed")
        self.gui.frontend['sh-btntrem'] = self.gui.glade.widgets.get_widget("btnStatsRemote")
        self.gui.frontend['sh-btntapp'] = self.gui.glade.widgets.get_widget("btnStatsApplication")
        self.gui.frontend['sh-btntfld'] = self.gui.glade.widgets.get_widget("btnStatsFolder")


        self.gui.frontend['sh-btntres'].connect('clicked', self.gui.actions.show_all_resources)
        self.gui.frontend['sh-btntcol'].connect('toggled', self.gui.actions.show_collection_view)
        self.gui.frontend['sh-btntsin'].connect('clicked', self.gui.actions.show_only_resources)
        self.gui.frontend['sh-btntclp'].connect('clicked', self.gui.actions.show_only_clipboard)
        self.gui.frontend['sh-btnttxt'].connect('clicked', self.gui.actions.show_only_text)
        self.gui.frontend['sh-btntimg'].connect('clicked', self.gui.actions.show_only_image)
        self.gui.frontend['sh-btntmus'].connect('clicked', self.gui.actions.show_only_audio)
        self.gui.frontend['sh-btntvdo'].connect('clicked', self.gui.actions.show_only_video)
        self.gui.frontend['sh-btntweb'].connect('clicked', self.gui.actions.show_only_web)
        self.gui.frontend['sh-btntfdd'].connect('clicked', self.gui.actions.show_only_feed)
        self.gui.frontend['sh-btntrem'].connect('clicked', self.gui.actions.show_only_remote)
        self.gui.frontend['sh-btntapp'].connect('clicked', self.gui.actions.show_only_application)
        self.gui.frontend['sh-btntfld'].connect('clicked', self.gui.actions.show_only_folder)


        # Set Stats labels
        self.gui.frontend['sh-ltotres'] = self.gui.glade.widgets.get_widget("lblTotResources")
        self.gui.frontend['sh-ltotcol'] = self.gui.glade.widgets.get_widget("lblTotCollection")
        self.gui.frontend['sh-ltotsin'] = self.gui.glade.widgets.get_widget("lblTotSingles")
        self.gui.frontend['sh-ltotclp'] = self.gui.glade.widgets.get_widget("lblTotClipboard")
        self.gui.frontend['sh-ltottxt'] = self.gui.glade.widgets.get_widget("lblTotText")
        self.gui.frontend['sh-ltotimg'] = self.gui.glade.widgets.get_widget("lblTotImage")
        self.gui.frontend['sh-ltotmus'] = self.gui.glade.widgets.get_widget("lblTotAudio")
        self.gui.frontend['sh-ltotvdo'] = self.gui.glade.widgets.get_widget("lblTotVideo")
        self.gui.frontend['sh-ltotweb'] = self.gui.glade.widgets.get_widget("lblTotWebsite")
        self.gui.frontend['sh-ltotfdd'] = self.gui.glade.widgets.get_widget("lblTotFeed")
        self.gui.frontend['sh-ltotrem'] = self.gui.glade.widgets.get_widget("lblTotRemote")
        self.gui.frontend['sh-ltotapp'] = self.gui.glade.widgets.get_widget("lblTotApplication")
        self.gui.frontend['sh-ltotfld'] = self.gui.glade.widgets.get_widget("lblTotFolder")

        # Set Stats Images
        self.gui.frontend['sh-itotres'] = self.gui.glade.widgets.get_widget("imgTotResources")
        self.gui.frontend['sh-itotcol'] = self.gui.glade.widgets.get_widget("imgTotCollection")
        self.gui.frontend['sh-itotsin'] = self.gui.glade.widgets.get_widget("imgTotSingles")
        self.gui.frontend['sh-imgtclp'] = self.gui.glade.widgets.get_widget("imgStatsClipboard")
        self.gui.frontend['sh-imgttxt'] = self.gui.glade.widgets.get_widget("imgStatsText")
        self.gui.frontend['sh-imgtimg'] = self.gui.glade.widgets.get_widget("imgStatsImage")
        self.gui.frontend['sh-imgtmus'] = self.gui.glade.widgets.get_widget("imgStatsAudio")
        self.gui.frontend['sh-imgtvdo'] = self.gui.glade.widgets.get_widget("imgStatsVideo")
        self.gui.frontend['sh-imgtweb'] = self.gui.glade.widgets.get_widget("imgStatsWebsite")
        self.gui.frontend['sh-imgtfdd'] = self.gui.glade.widgets.get_widget("imgStatsFeed")
        self.gui.frontend['sh-imgtrem'] = self.gui.glade.widgets.get_widget("imgStatsRemote")
        self.gui.frontend['sh-imgtapp'] = self.gui.glade.widgets.get_widget("imgStatsApplication")
        self.gui.frontend['sh-imgtfld'] = self.gui.glade.widgets.get_widget("imgStatsFolder")

        self.gui.frontend['sh-itotres'].set_from_pixbuf(self.gui.icons.get_icon_by_name('Desktop.svg', 24, 24))
        self.gui.frontend['sh-itotcol'].set_from_pixbuf(self.gui.icons.get_icon_by_name('Collection.svg', 24, 24))
        self.gui.frontend['sh-itotsin'].set_from_pixbuf(self.gui.icons.get_icon_by_name('opml.svg', 24, 24))
        self.gui.frontend['sh-imgtclp'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Clipboard'], 24, 24))
        self.gui.frontend['sh-imgttxt'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['TextDocument'], 24, 24))
        self.gui.frontend['sh-imgtimg'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Image'], 24, 24))
        self.gui.frontend['sh-imgtmus'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Audio'], 24, 24))
        self.gui.frontend['sh-imgtvdo'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Video'], 24, 24))
        self.gui.frontend['sh-imgtweb'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Website'], 24, 24))
        self.gui.frontend['sh-imgtfdd'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Feed'], 24, 24))
        self.gui.frontend['sh-imgtrem'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['RemoteDataObject'], 24, 24))
        self.gui.frontend['sh-imgtapp'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Application'], 24, 24))
        self.gui.frontend['sh-imgtfld'].set_from_pixbuf(self.gui.icons.get_icon_by_name(NFO['Folder'], 24, 24))

        # SPARQL Queries Widgets
        self.gui.frontend['sh-scolclipstats'] = self.gui.glade.widgets.get_widget("cntColClipStats")
        self.gui.frontend['sh-clipboard'] = self.gui.glade.widgets.get_widget("cntClipboard")
        self.gui.frontend['sh-collections'] = self.gui.glade.widgets.get_widget("cntCollections")
        self.gui.frontend['sh-resources'] = self.gui.glade.widgets.get_widget("cntLastResources")

        # Resources List & Iconview buttons
        # Back button
        #self.gui.frontend['sh-imgback'] = self.gui.glade.widgets.get_widget("imgBack")
        #self.gui.frontend['sh-imgback'].set_from_stock(gtk.STOCK_GO_BACK, gtk.ICON_SIZE_SMALL_TOOLBAR)
        self.gui.frontend['sh-btnback'] = self.gui.glade.widgets.get_widget("btnBack")
        self.gui.frontend['sh-btnback'].connect('clicked', self.gui.actions.show_previous_view)

        # Cloud
        self.gui.frontend['sh-lfilterdes'] = self.gui.glade.widgets.get_widget("lblFilterDesc")
        self.gui.frontend['sh-frmfilter'] = self.gui.glade.widgets.get_widget("frmFilter")
        self.gui.frontend['sh-cmbqnames'] = self.gui.glade.widgets.get_widget("cmbQNames")
        self.gui.frontend['sh-cmbqnames'].connect('changed', self.gui.actions.activate_filter)
        self.gui.frontend['sh-cntcloud'] = self.gui.glade.widgets.get_widget("cntCloud")
        self.gui.frontend['sh-cmbfdate'] = self.gui.glade.widgets.get_widget("cmbFilterDate")
        self.gui.frontend['sh-cmbfdate'].connect('changed', self.gui.actions.activate_date_filter)

        # right shortcut menu
        #self.gui.frontend['sh-btncol'] = self.gui.glade.widgets.get_widget("btnCollection")
        #self.gui.frontend['sh-btncol'].connect('toggled', self.gui.actions.show_collection_view)
        self.gui.frontend['sh-collection'] = self.gui.glade.widgets.get_widget("Collections")

    def search(self, search_entry):
        t1 = datetime.datetime.now()
        search_term = search_entry.get_text()

        if len(search_term) > 1:
            filter_view = self.gui.frontend['sh-chkfltview'].get_active()

            if filter_view:
                resources = self.gui.frontend['view']['selected']
                graph = self.gui.ask.create_temporal_graph(resources)
            else:
                graph = None

            query = get_search_query(search_term)
            result = self.gui.ask.this(query, graph)
            if result is not None:
                t2 = datetime.datetime.now()
                tf1 = t2 - t1
                t1 = datetime.datetime.now()
                self.gui.frontend['view']['selected'] = result.selected
                self.gui.frontend['view']['query'] = query
                self.gui.actions.update_gui(False)
                t2 = datetime.datetime.now()
                tf2 = t2 - t1
                text = "<b>Search</b>: <i>%s secs</i>\t\t<b>GUI</b>: <i>%s secs</i>" % (tf1, tf2)
                self.gui.statusbar.set_text(text)

    def filter_only_current_view(self, *args):
        print args



    def update_stats(self, graph):
        try:
            t1 = datetime.datetime.now()
            ltotres = self.gui.ask.get_total_resources(graph)
            ltotcol = self.gui.ask.get_total_collections(graph)
            ltotsin = self.gui.ask.get_total_singles(graph)

            self.gui.frontend['sh-btntclp'].hide_all()
            self.gui.frontend['sh-btnttxt'].hide_all()
            self.gui.frontend['sh-btntimg'].hide_all()
            self.gui.frontend['sh-btntmus'].hide_all()
            self.gui.frontend['sh-btntvdo'].hide_all()
            self.gui.frontend['sh-btntweb'].hide_all()
            self.gui.frontend['sh-btntfdd'].hide_all()
            self.gui.frontend['sh-btntrem'].hide_all()
            self.gui.frontend['sh-btntapp'].hide_all()
            self.gui.frontend['sh-btntfld'].hide_all()

            if graph:
                ltotclp = self.gui.ask.get_total_clipboard(graph)
                if ltotclp > 0:
                    self.gui.frontend['sh-btntclp'].set_no_show_all(False)
                    self.gui.frontend['sh-btntclp'].show_all()

                ltottxt = self.gui.ask.get_total_text(graph)
                if ltottxt > 0:
                    self.gui.frontend['sh-btnttxt'].set_no_show_all(False)
                    self.gui.frontend['sh-btnttxt'].show_all()

                ltotimg = self.gui.ask.get_total_images(graph)
                if ltotimg > 0:
                    self.gui.frontend['sh-btntimg'].set_no_show_all(False)
                    self.gui.frontend['sh-btntimg'].show_all()

                ltotmus = self.gui.ask.get_total_audio(graph)
                if ltotmus > 0:
                    self.gui.frontend['sh-btntmus'].set_no_show_all(False)
                    self.gui.frontend['sh-btntmus'].show_all()

                ltotvdo = self.gui.ask.get_total_videos(graph)
                if ltotvdo > 0:
                    self.gui.frontend['sh-btntvdo'].set_no_show_all(False)
                    self.gui.frontend['sh-btntvdo'].show_all()

                ltotapp = self.gui.ask.get_total_application(graph)
                if ltotapp > 0:
                    self.gui.frontend['sh-btntapp'].set_no_show_all(False)
                    self.gui.frontend['sh-btntapp'].show_all()

                ltotweb = self.gui.ask.get_total_website(graph)
                if ltotweb > 0:
                    self.gui.frontend['sh-btntweb'].set_no_show_all(False)
                    self.gui.frontend['sh-btntweb'].show_all()

                ltotfdd = self.gui.ask.get_total_feed(graph)
                if ltotfdd > 0:
                    self.gui.frontend['sh-btntfdd'].set_no_show_all(False)
                    self.gui.frontend['sh-btntfdd'].show_all()

                ltotrem = self.gui.ask.get_total_remote(graph)
                if ltotrem > 0:
                    self.gui.frontend['sh-btntrem'].set_no_show_all(False)
                    self.gui.frontend['sh-btntrem'].show_all()

                ltotfld = self.gui.ask.get_total_folder(graph)
                if ltotfld > 0:
                    self.gui.frontend['sh-btntfld'].set_no_show_all(False)
                    self.gui.frontend['sh-btntfld'].show_all()
            else:
                ltotclp = 0
                ltottxt = 0
                ltotimg = 0
                ltotmus = 0
                ltotvdo = 0
                ltotapp = 0
                ltotweb = 0
                ltotfdd = 0
                ltotrem = 0
                ltotfld = 0


            self.gui.frontend['sh-ltotres'].set_label('<small>' + str(ltotres) + '</small>')
            self.gui.frontend['sh-ltotcol'].set_label('<small>' + str(ltotcol) + '</small>')
            self.gui.frontend['sh-ltotsin'].set_label('<small>' + str(ltotsin) + '</small>')
            self.gui.frontend['sh-ltotclp'].set_label('<small>' + str(ltotclp) + '</small>')
            self.gui.frontend['sh-ltottxt'].set_label('<small>' + str(ltottxt) + '</small>')
            self.gui.frontend['sh-ltotimg'].set_label('<small>' + str(ltotimg) + '</small>')
            self.gui.frontend['sh-ltotmus'].set_label('<small>' + str(ltotmus) + '</small>')
            self.gui.frontend['sh-ltotvdo'].set_label('<small>' + str(ltotvdo) + '</small>')
            self.gui.frontend['sh-ltotweb'].set_label('<small>' + str(ltotweb) + '</small>')
            self.gui.frontend['sh-ltotfdd'].set_label('<small>' + str(ltotfdd) + '</small>')
            self.gui.frontend['sh-ltotrem'].set_label('<small>' + str(ltotrem) + '</small>')
            self.gui.frontend['sh-ltotfld'].set_label('<small>' + str(ltotfld) + '</small>')
            self.gui.frontend['sh-ltotapp'].set_label('<small>' + str(ltotapp) + '</small>')
            t2 = datetime.datetime.now()
            delta = t2 - t1
            #print "updating stats took: %s" % delta
        except Exception, error:
            pass #print "update_stats", error
            #raise


    def update_resources_list(self, filterdate, query=None):
        t1 = datetime.datetime.now()
        now = str(t1)[0:19]

        if not query:
            if filterdate:
                filter = self.gui.actions.get_date_filter()
                query = get_date_filtered_query(int(filter))
            else:
                query = get_normal_query()

        try:
            selected_resources = self.gui.frontend['view']['selected']
            tgraph = self.gui.ask.create_temporal_graph(selected_resources)
            result = tgraph.query(query)
            self.gui.frontend['view']['current'] = result.selected
        except Exception, error:
            result = self.gui.ask.this(query)
            self.gui.frontend['view']['current'] = result.selected

        ncols = len(result.selectionF)
        # add columns to GenericView. I insert and additional column for icons.
        columns = {}
        columns[0] = ('Id', gtk.CellRendererText())
        columns[1] = ('', gtk.CellRendererPixbuf())
        columns[2] = ('Collected', gtk.CellRendererText())
        columns[3] = ('Title', gtk.CellRendererText())

        # Fill GenericView
        now = datetime.datetime.now()
        resources = []
        try:
            view = self.gui.frontend['preferences']['resources_view']
        except:
            view = 'iconview'

        for id in self.gui.frontend['view']['current']:
            try:
                vres = self.gui.app.vstore.get_virtual_resource(id)
                if view == 'iconview':
                    text = "<b>" + str(vres.prop[NIE['title']][0]) + "</b>"
                    text += "\n<small><i>" + str(fuzzy_date(vres.prop[NAO['created']][0])) + "</i></small>"
                    date = vres.prop[NAO['created']][0]
                else:
                    text = str(vres.prop[NIE['title']][0])
                    date = fuzzy_date(vres.prop[NAO['created']][0])
                icon = self.gui.icons.get_icon_by_name(vres.prop[RDF.type][0])
                alist = []
                alist.append(vres.get_id())
                alist.append(icon)
                alist.append(date)
                alist.append(text.decode('utf-8'))
                resources.append(alist)
            except Exception, error:
                pass #print "update_resources_list", error

        if view == 'iconview':
            customview = IconView(self.gui, columns, resources)
        else:
            customview = ListView(self.gui, columns, resources)

        old = self.gui.frontend['sh-resources'].get_children()
        if old:
            self.gui.frontend['sh-resources'].remove(old[0])

        self.gui.frontend['sh-resources'].add(customview)
        self.gui.frontend['sh-resources'].show_all()

        t2 = datetime.datetime.now()
        delta = t2 - t1
        #print "updating resources list took: %s" % delta
